import { Button, Card, Form, Input, Modal, Table, Tag, Upload, message, Image } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import React, { useState } from 'react';
import type { UploadFile, UploadProps } from 'antd';

type Habit = {
  id: string;
  name: string;
  frequency: string;
  completed: boolean;
  streak: number;
  imageUrl?: string;
};

export default function HabitsPage() {
  const [habits, setHabits] = useState<Habit[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();

  const columns = [
    { title: '习惯名称', dataIndex: 'name', key: 'name' },
    { title: '频率', dataIndex: 'frequency', key: 'frequency' },
    {
      title: '图片',
      key: 'imageUrl',
      render: (record: Habit) => (
        record.imageUrl ? 
        <Image src={record.imageUrl} alt={record.name} width={50} height={50} style={{ objectFit: 'cover' }} /> : 
        <span>无图片</span>
      )
    },
    {
      title: '状态',
      key: 'completed',
      render: (record: Habit) => (
        <Tag color={record.completed ? '#4CAF50' : 'default'}>
          {record.completed ? '已完成' : '未完成'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (record: Habit) => (
        <>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          />
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDelete(record.id)}
          />
          <Button
            type="primary"
            style={{ marginLeft: 8 }}
            onClick={() => handleCheckIn(record.id)}
          >
            打卡
          </Button>
        </>
      )
    }
  ];

  const handleCheckIn = (id: string) => {
    setHabits(prev => prev.map(h => 
      h.id === id ? { ...h, completed: true, streak: h.streak + 1 } : h
    ));
  };

  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [imageUrl, setImageUrl] = useState<string>();

  const handleUploadChange: UploadProps['onChange'] = ({ fileList: newFileList, file }) => {
    setFileList(newFileList);
    
    if (file.status === 'done') {
      // 模拟上传成功后获取URL
      // 在实际应用中，这里应该是从服务器响应中获取URL
      const url = URL.createObjectURL(file.originFileObj as Blob);
      setImageUrl(url);
      message.success(`${file.name} 上传成功`);
    } else if (file.status === 'error') {
      message.error(`${file.name} 上传失败`);
    }
  };

  const uploadProps: UploadProps = {
    beforeUpload: (file) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件!');
        return Upload.LIST_IGNORE;
      }
      return false; // 阻止自动上传
    },
    fileList,
    onChange: handleUploadChange,
    maxCount: 1,
  };

  const handleSubmit = (values: Omit<Habit, 'id' | 'completed' | 'streak' | 'imageUrl'>) => {
    const newHabit = {
      ...values,
      id: Date.now().toString(),
      completed: false,
      streak: 0,
      imageUrl: imageUrl
    };
    setHabits(prev => [...prev, newHabit]);
    setIsModalVisible(false);
    form.resetFields();
    setFileList([]);
    setImageUrl(undefined);
  };

  return (
    <div style={{ padding: 24 }}>
      <Card 
        title="习惯管理"
        extra={
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={() => setIsModalVisible(true)}
          >
            新建习惯
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={habits}
          rowKey="id"
          pagination={false}
        />
      </Card>

      <Modal
        title="添加习惯"
        visible={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
      >
        <Form form={form} onFinish={handleSubmit}>
          <Form.Item
            name="name"
            label="习惯名称"
            rules={[{ required: true }]}
          >
            <Input placeholder="请输入习惯名称" />
          </Form.Item>
          <Form.Item
            name="frequency"
            label="执行频率"
            rules={[{ required: true }]}
          >
            <Input placeholder="例如：每天1次" />
          </Form.Item>
          <Form.Item
            name="image"
            label="上传图片"
          >
            <Upload
              {...uploadProps}
              listType="picture-card"
            >
              {fileList.length < 1 && (
                <div>
                  <UploadOutlined />
                  <div style={{ marginTop: 8 }}>上传图片</div>
                </div>
              )}
            </Upload>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}